package com.example.night.service.MysqlService.PromoteGoods;

import com.example.night.data.Good.GoodsRanking;
import com.example.night.data.promoteGood.SalesRanking;
import com.example.night.data.promoteGood.SalesRankingRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SalesRankingMysqlService {

    @Autowired
    private SalesRankingRepository rankingRepository;

    // ✅ 修改 save 方法，接收 List<GoodsRanking> 并转换
    public void save(List<GoodsRanking> goodsRankingList, String date) {
        for (GoodsRanking goodsRanking : goodsRankingList) {
            SalesRanking ranking = new SalesRanking();

            // 设置商品信息
            ranking.setGoodPackage(goodsRanking.getGoodPackage());  // 直接将 Goods 对象存入

            // 设置商品排名
            ranking.setRanking(goodsRanking.getRanking());

            ranking.setSellNum(goodsRanking.getOrderNum());
            ranking.setOrderMoney(goodsRanking.getOrderMoney());

            // 设置日期
            ranking.setDate(stringToDate(date));

            // 保存到数据库
            rankingRepository.save(ranking);
        }
    }

    public static Date stringToDate(String dateString) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); // 根据你的日期格式定义
        try {
            return formatter.parse(dateString); // 将字符串解析为 Date 对象
        } catch (ParseException e) {
            e.printStackTrace();
            return null; // 解析失败时返回 null 或抛出异常
        }
    }
    // ✅ 修改 findByDate 方法，返回 List<GoodsRanking>
    public List<GoodsRanking> findByDate(Date date) {
        // 查询数据库中的 SalesRanking
        List<SalesRanking> rankings = rankingRepository.findByDate(date);

        // 将查询结果转换为 GoodsRanking 列表
        return rankings.stream()
                .map(ranking -> new GoodsRanking(ranking.getGoodPackage(), ranking.getRanking()))
                .collect(Collectors.toList());
    }

    // 查询指定日期范围内的数据
    public List<GoodsRanking> findSalesRankingsByDateRange(Date startDate, Date endDate) {
        List<SalesRanking> rankings = rankingRepository.findByDateBetween(startDate, endDate);

        List<GoodsRanking> goodsRankings = new ArrayList<>();

        for (SalesRanking ranking : rankings) {
            GoodsRanking goodsRanking = new GoodsRanking();
            goodsRanking.setGoodPackage(ranking.getGoodPackage());
            goodsRanking.setRanking(ranking.getRanking());
            goodsRanking.setOrderNum(ranking.getSellNum());
            goodsRanking.setOrderMoney(ranking.getOrderMoney());

            goodsRankings.add(goodsRanking);
        }
        return goodsRankings;
    }
}
